package com.teacher.hong.servlet;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 上传图片
 */
@MultipartConfig
//@WebServlet("/fileUpload")
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("开始上传...");
        Part part = req.getPart("imgFile");   //根据参数获取上传文件部件
//        String fileName = part.getSubmittedFileName();  //获取图片本身的文件名
        String fileName = new Date().getTime() + ".jpg";
        System.out.println("fileName:" + fileName);
        //设置文件保存的路径
        String uploadPath = getServletContext().getInitParameter("uploadPath");
        File fileFolderPath = new File(uploadPath);
        if (!fileFolderPath.exists()) fileFolderPath.mkdirs();  //如果上传路径不存在，则创建上传路径
        System.out.println("uploadPath:" + uploadPath);
        //上传图片到指定的路径
        part.write(uploadPath + "/" + fileName);


        JSONObject object = new JSONObject(true);
        object.put("state", 200);
        object.put("value", "/upload/" + fileName);
        object.put("timestamp", LocalDateTime.now());
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(object.toJSONString());
    }
}
